import 'package:gold/app/user_provider.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_gold.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/goods_detail_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';

/// @description:
/// @author tangzhentao
/// @created at 13:38 2024/11/30

class IntegralGoodsViewmodel extends Viewmodel {
  /// 积分商品id
  final int goodsId;

  /// 轮播坐标
  int _carouselIndex = 0;
  int get carouselIndex => _carouselIndex;
  set carouselIndex(int value) {
    if (_carouselIndex != value) {
      _carouselIndex = value;
      notifyListeners();
    }
  }

  /// 数量
  int _number = 1;
  int get number => _number;
  set number(int value) {
    if (_number != value) {
      _number = value;
      _calInsufficient();
      notifyListeners();
    }
  }

  bool _insufficient = false;
  /// 积分不足
  bool get insufficient => _insufficient;

  /// 商品详情
  GoodsDetailModel? detail;

  IntegralGoodsViewmodel(this.goodsId) {
    _calInsufficient();
  }

  /// 计算积分不足
  void _calInsufficient() {
    final user = XfgNav.read<UserProvider>().user;
    final points = ((detail?.pointsPrice?? 0) * _number).toInt();
    _insufficient = (user.points?? 0) < points;
  }

  /// 加载数据
  Future loadData() async {
    setLoading();
    final result = await Http().request<GoodsDetailModel>(ApiGold.pointsDetail, data: {'id': goodsId});
    if (result.success) {
      detail = result.data;
      if (detail != null) {
        setSuccess();
      } else {
        setEmpty();
      }
    } else {
      setFailed(msg: result.msg);
    }
  }

  /// 立即兑换
  Future exchangeNow() async {
    XfgNav.pushNamed(Routes.integralGoodsOrder, arguments: {'number': _number, 'goods': detail!});
  }

  @override
  onReload() => loadData();

  @override
  onRetry() => loadData();
}
